﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Xml.Linq;

namespace Web.Core.HttpHandlers
{
    /// <summary>
    /// Summary description for File
    /// </summary>
    public class FileHttpHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            
            XElement file = context.Session[context.Request.QueryString["id"]] as XElement;

            string filePath = string.Format("...\\{0}\\{1}", context.Request.QueryString["dt"/*DocumentType*/], file.Attribute("ID").Value);
            string fileName = file.Attribute("FileName").Value;
            string contentType = file.Attribute("ContentType").Value;
            string contentLength = file.Attribute("ContentLength").Value;

            context.WriteFile(filePath, fileName, contentType, contentLength);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

    public static class HttpContextExtension
    {
        public static void WriteFile(this HttpContext context, string filePath, string fileName, string contentType, string contentLength)
        {
            
            using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                long fileSize = fs.Length;
                int bytesRead;
                long totalBytesRead = 0;
                byte[] dataBlock = new byte[4096];

                context.Response.Clear();
                context.Response.ContentType = contentType;
                context.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
                context.Response.AppendHeader("content-length", contentLength);

                while (totalBytesRead < fileSize)
                {
                    if (!context.Response.IsClientConnected)
                        break;

                    bytesRead = fs.Read(dataBlock, 0, dataBlock.Length);
                    context.Response.OutputStream.Write(dataBlock, 0, bytesRead);
                    context.Response.Flush();
                    totalBytesRead += bytesRead;
                }

                context.Response.Close();
            }
        }

    }
}